package com.wms.service.common;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wms.dao.WProductDao;
import com.wms.dao.WStoreDao;
import com.wms.entity.WProduct;
import com.wms.entity.WStore;
import com.wms.mytool.Result;
import com.wms.service.CommonService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author li xiaoYu
 */
@Service("wStockCommonService")
public class WStockCommonService implements CommonService {
    @Resource
    private WStoreDao wStoreDao;
    @Resource
    private WProductDao wProductDao;

    /**
     * 修改商品、仓库库存信息
     * @param sid 仓库id
     * @param pid 商品id
     * @param entryNum 出入库数量
     * @param flag true为入库，false为出库
     * @return 实例对象
     */
    public Result updateStock(Integer sid,Integer pid,Integer entryNum,boolean flag) {
        //仓库库存增加
        QueryWrapper<WStore> qw = Wrappers.query();
        qw.eq("store_id", sid);
        WStore store = this.wStoreDao.selectOne(qw);
        if (flag?store.getUseNum() + entryNum > store.getMaxNum():store.getUseNum() - entryNum < 0) {
            return new Result(400, null, flag?"超过仓库最大库存":"超出仓库库存量");
        } else {
            //商品库存增加
            QueryWrapper<WProduct> query = Wrappers.query();
            query.eq("product_id", pid);
            WProduct product = this.wProductDao.selectOne(query);
            if (flag?product.getNum() + entryNum > product.getMaxNum():product.getNum() - entryNum <product.getMinNum()) {
                return new Result(400, null, flag?"超过商品最大库存":"超出商品库存量");
            } else {
                Date date = new Date();
                product.setUpdateTime(date);
                product.setNum(flag?product.getNum() + entryNum:product.getNum() - entryNum);
                this.wProductDao.updateById(product);
                store.setUpdateTime(date);
                store.setUseNum(flag?store.getUseNum() + entryNum:store.getUseNum() - entryNum);
                this.wStoreDao.updateById(store);
                return new Result(200, null, "库存增加");
            }
        }
    }
}
